import { getUniqueDeviceId, isInWebview } from "~/utils/helper";

export type TrackDataType = {
  udid?: string;
  category: string;
  action: string;
  opt_label: string;
  opt_value?: number;
  appId?: number;
  opt_extra?: {
    [k in string]: any;
  };
};

export const useTrackApi = () => {
  const route = useRoute();

  const track = (data: TrackDataType) => {
    const ttcid = route.query.ttcid || route.query.fbclid;
    const { $globalData } = useNuxtApp();
    const runtimeConfig = useRuntimeConfig();

    const optExtra = Object.assign(
      {
        event_time: Date.now(),
        ua: getUniqueDeviceId(),
        in_webview: isInWebview(),
        version: runtimeConfig.public.version,
        strategy: runtimeConfig.public.strategy,
        ttclid: ttcid,
        current_path: route.fullPath,
      },
      data.opt_extra,
    );

    return useHttp({
      method: "POST",
      url: "/track/event",
      data: {
        optExtra: optExtra,
        category: data.category,
        optValue: data.opt_value,
        optLabel: data.opt_label,
        action: data.action,
        udid: $globalData.userId,
        appId: runtimeConfig.public.strategy,
      },
    });
  };

  return { track };
};
